function _slicedToArray(arr, i) {
  return (
    _arrayWithHoles(arr) ||
    _iterableToArrayLimit(arr, i) ||
    _unsupportedIterableToArray(arr, i) ||
    _nonIterableRest()
  );
}
function _nonIterableRest() {
  throw new TypeError(
    'Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.',
  );
}
function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === 'string') return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === 'Object' && o.constructor) n = o.constructor.name;
  if (n === 'Map' || n === 'Set') return Array.from(o);
  if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
    return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit(arr, i) {
  var _i =
    null == arr
      ? null
      : ('undefined' != typeof Symbol && arr[Symbol.iterator]) || arr['@@iterator'];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (((_x = (_i = _i.call(arr)).next), 0 === i)) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else
        for (
          ;
          !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i);
          _n = !0
        );
    } catch (err) {
      (_d = !0), (_e = err);
    } finally {
      try {
        if (!_n && null != _i.return && ((_r = _i.return()), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
import classnames from 'classnames';
import React, { useCallback, useLayoutEffect, useRef, useState } from 'react';
import './index.less';
var px2Num = function px2Num(px) {
  return typeof px === 'number' ? px : Number(px.replace('px', ''));
};

/**
 * 文本省略
 * @issue
 * @param param0
 * @returns
 */
export default function Ellipsis(_ref) {
  var _defaultExpanded;
  var className = _ref.className,
    style = _ref.style,
    content = _ref.content,
    _ref$expandText = _ref.expandText,
    expandText = _ref$expandText === void 0 ? '展开' : _ref$expandText,
    _ref$collapseText = _ref.collapseText,
    collapseText = _ref$collapseText === void 0 ? '收起' : _ref$collapseText,
    defaultExpanded = _ref.defaultExpanded,
    _ref$rows = _ref.rows,
    rows = _ref$rows === void 0 ? 1 : _ref$rows;
  var _useState = useState(true),
    _useState2 = _slicedToArray(_useState, 2),
    expandable = _useState2[0],
    setExpandable = _useState2[1];
  var _useState3 = useState(
      (_defaultExpanded = !!defaultExpanded) !== null && _defaultExpanded !== void 0
        ? _defaultExpanded
        : false,
    ),
    _useState4 = _slicedToArray(_useState3, 2),
    expanded = _useState4[0],
    setExpanded = _useState4[1];
  var _useState5 = useState(content),
    _useState6 = _slicedToArray(_useState5, 2),
    ellipsisText = _useState6[0],
    setEllipsisText = _useState6[1];
  var containerRef = useRef(null);
  var refresh = useCallback(
    function () {
      if (containerRef.current) {
        var _style = window.getComputedStyle(containerRef.current);
        var width = px2Num(_style.width);
        var height = px2Num(_style.height);
        var vnode = document.createElement('div');
        vnode.style.setProperty('font-family', _style.fontFamily);
        vnode.style.setProperty('font-weight', _style.fontWeight);
        vnode.style.setProperty('font-size', _style.fontSize);
        vnode.style.setProperty('letter-spacing', _style.letterSpacing);
        vnode.style.setProperty('line-height', _style.lineHeight);
        vnode.style.setProperty('width', 'max-content');
        vnode.style.setProperty('word-break', 'break-all');
        vnode.style.setProperty('text-wrap', 'no-wrap');
        vnode.textContent = content;
        document.body.appendChild(vnode);
        var vnodeStyle = window.getComputedStyle(vnode);
        var vnodeWidth = px2Num(vnodeStyle.width);
        var vnodeHeight = px2Num(vnodeStyle.height);

        // 如果当前高度小于行数，则无需展开折叠
        if (height <= vnodeHeight * rows || !content.length) {
          setExpandable(false);
        }

        // 单行文本字数
        var singleRowLength = content.length * (width / vnodeWidth);
        // 指定行数文本字数
        var rowsLength = singleRowLength * rows;
        // 调整偏移量
        var adjustOffset = 3;

        // 折叠展示文本初始值
        var expandedLength = rowsLength - (expandText.length + adjustOffset);
        if (expandedLength < 0 || isNaN(expandedLength)) expandedLength = 0;
        expandedLength = Math.round(expandedLength);

        // 使 vnode 与 szzj-ellipsis 容器等宽
        vnode.style.width = width + 'px';
        var text = '';
        var currentHeight = 0;
        var prevExpandedLength = 0;

        // 将折叠文本赋值给 vnode，以测量实际高度
        var setExpandedTextToVnode = function setExpandedTextToVnode(currentExpandedLength) {
          prevExpandedLength = expandedLength;
          text = content.slice(0, currentExpandedLength) + '...';
          // ' ' 对应 a 标签内 &nbsp;
          vnode.textContent = ''.concat(text, ' ').concat(expandText);
          currentHeight = px2Num(window.getComputedStyle(vnode).height);
        };
        setExpandedTextToVnode(expandedLength);
        if (currentHeight <= rows * vnodeHeight) {
          while (currentHeight <= rows * vnodeHeight && expandedLength < content.length - 1) {
            var nextExpandedLength = expandedLength + 1;
            setExpandedTextToVnode(nextExpandedLength);
            if (currentHeight <= rows * vnodeHeight) {
              expandedLength = nextExpandedLength;
            } else {
              // 调整后，过高则回退
              text = content.slice(0, prevExpandedLength) + '...';
            }
          }
        } else {
          while (currentHeight > rows * vnodeHeight && expandedLength < content.length - 1) {
            var _nextExpandedLength = expandedLength - 1;
            setExpandedTextToVnode(_nextExpandedLength);
            if (currentHeight > rows * vnodeHeight) {
              expandedLength = _nextExpandedLength;
            }
          }
        }
        setEllipsisText(text);
        document.body.removeChild(vnode);
      }
    },
    [content, defaultExpanded, expandText],
  );
  useLayoutEffect(function () {
    refresh();
  }, []);

  // TODO: 监听 resize，调整折叠文本

  return /*#__PURE__*/ React.createElement(
    'div',
    {
      className: classnames('szzj-ellipsis', className),
      style: style,
      ref: containerRef,
    },
    !expandable || expanded ? content : ellipsisText,
    expandable &&
      /*#__PURE__*/ React.createElement(
        'a',
        {
          className: 'szzj-ellipsis-expand',
          onClick: function onClick() {
            return setExpanded(!expanded);
          },
        },
        '\xA0',
        expanded ? collapseText : expandText,
      ),
  );
}
